﻿using CBS.Common;
using CBS.DB;
using CBS.DB.CBSEntity;
using CBS.Model.ManageModel;
using CBS.Model.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace CBS.APP
{
    public class GradeApp
    {
        public static bool AddGrade(GradeViewModel grade)
        {
            CBSContext ctx = new();
            ctx.cbs_grade.Add(new cbs_grade
            {
                GradeName = grade.GradeName,
            });

            return ctx.SaveChanges() > 0;
        }


        public static bool DeleteGrade(int GradeId, out string msg)
        {
            msg = "";
            CBSContext ctx = new CBSContext();
            if (ctx.cbs_course_plan.Any(t => t.GradeId == GradeId)) 
            {
                msg = "数据已经被使用，不能删除。";
                return false;
            }
            ctx.Remove(ctx.cbs_grade.First(t => t.GradeId == GradeId));

            return ctx.SaveChanges() > 0;
        }

        public static List<GradeViewModel> GetSelectList()
        {
            CBSContext ctx = new();
            var data = (from gra in ctx.cbs_grade
                        select new GradeViewModel
                        {
                            GradeId = gra.GradeId,
                            GradeName = gra.GradeName
                        }).ToList();

            if (data != null)
            {
                return data;
            }
            return new List<GradeViewModel>();
            
        }

        public static List<GradeViewModel> GetList(Pagination page, string? keyword)
        {
            if (string.IsNullOrWhiteSpace(keyword))
            {
                return GetList(null, page);
            }
            else
            {
                return GetList(t => t.GradeName.Contains(keyword), page);
            }
        }

        public static List<GradeViewModel> GetList(Expression<Func<cbs_grade, bool>>? predicate, Pagination page)
        {
            List<cbs_grade> list;
            RepositoryBase<cbs_grade> repo = new();
            if (predicate == null)
            {
                list = repo.FindList(page);
            }
            else
            {
                list = repo.FindList(predicate, page);
            }


            return PropertyHelper.Assignment<GradeViewModel, cbs_grade>(list);
        }
    }
}
